//
//  EpointSettingViewController.m
//  EpointFrame5
//
//  Created by 李亚春 on 13-12-17.
//  Copyright (c) 2013年 Epoint. All rights reserved.
//

#import "EpointSettingViewController.h"
#import "EpointAboutViewController.h"
#import "EpointUpdateService.h"
#import "TDBadgedCell.h"
#import "EpointSettingModel.h"
#import "EpointIOUtil.h"
#import "EpointCacheDB.h"
#import "EpointInputViewController.h"
#import "EpointSinglePickerViewController.h"
#import "EAD_About_ViewController.h"
#import "RIButtonItem.h"
#import "UIAlertView+Blocks.h"

#define SynTaskId 1234
#define SetCheckUpdateTaskId 2
#define FrameFeedBackTaskId 3
#define DeletePushTokenTaskId 1235


@interface EpointSettingViewController ()
{
    UITableView *tv;
    NSMutableArray *dataArray;
}
@end

@implementation EpointSettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    dataArray = [[NSMutableArray alloc]init];
    [self generateSetingData];
    tv = [[UITableView alloc]initWithFrame:[self getFullContentFrame] style:UITableViewStyleGrouped];
    
    tv.dataSource = self;
    tv.delegate = self;
    tv.backgroundView = nil;
    tv.backgroundColor = [UIColor clearColor];
    [self.view setBackgroundColor:COLOR(239, 239, 243)];
    
    [self.view addSubview:tv];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath indexAtPosition:0]==0) {
        static NSString *CellIdentifier = @"Cell";
        TDBadgedCell *cell = [[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        EpointSettingModel *d = [dataArray objectAtIndex:indexPath.row];
        cell.textLabel.text = d.title;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        NSString *badgeStr = d.badge;
        if (badgeStr.length>0) {
            cell.badgeString = badgeStr;
            cell.badgeColor = COLOR(30, 144, 255);
        }
        return cell;
    }
    else if ([indexPath indexAtPosition:0]==1)
    {
        static NSString *identifier = @"simplecell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell==nil) {
            cell = [[UITableViewCell alloc]init];
        }
        cell.textLabel.text = @"退出当前账号";
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.textColor = [UIColor redColor];
        //蓝色
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        return cell;
    }
    return nil;
}

//数据同步
+(void)synData:(EpointPhoneViewController *)vc
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *syndate = [ud objectForKey:Epoint_Syn_Date];
    if (syndate.length==0) {
        [vc showMBPHUDWithMessage:@"正在同步数据..."];
        [vc startTask:@"EpointSynTask" withParams:nil withTaskId:SynTaskId];
    }
}

-(void)generateSetingData
{
    [dataArray removeAllObjects];
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *syndate = [ud objectForKey:Epoint_Syn_Date];
    if (syndate.length==0) {
        syndate = @"未同步";
    }
    EpointSettingModel *set = [[EpointSettingModel alloc]initWithTitle:@"数据同步" detail:@"" badge:syndate setClick:^{
        [self showMBPHUDWithMessage:@"正在同步数据..."];
        [self startTask:@"EpointSynTask" withParams:nil withTaskId:SynTaskId];
    }];
    [dataArray addObject:set];
    
    EpointSettingModel *noti = [[EpointSettingModel alloc]initWithTitle:@"消息通知" detail:@"" badge:@"" setClick:^{
        RIButtonItem *okItem = [RIButtonItem item];
        okItem.label = @"确定";
        
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"打开或关闭消息通知，请到iOS设置-通知中心进行配置！" cancelButtonItem:nil otherButtonItems:okItem,nil];
        
        [alter show];
    }];
    [dataArray addObject:noti];
    
//    if (!CurrentDeviceISiPad) {
        int selectColorIndex = [[DBFrameService getConfigValue:Epoint_User_ThemeColor]intValue];
        NSString *selectColorName = [self.themeColorStr objectAtIndex:selectColorIndex];
        EpointSettingModel *themeManage = [[EpointSettingModel alloc]initWithTitle:@"主题颜色" detail:@"" badge:selectColorName setClick:^{
            [EpointSinglePickerViewController InvokeSinglePickerViewController:self title:@"主题选择" strArr:self.themeColorStr handler:^(int index){
                [DBFrameService setConfigValue:Epoint_User_ThemeColor value:[NSString stringWithFormat:@"%i",index]];
                [self generateSetingData];
                [tv reloadData];
            }];
        }];
        [dataArray addObject:themeManage];
//    }
    /*
    long long cacheLength = [EpointIOUtil fileSizeAtPath:[EpointCacheDB getDBFilePath]];
    NSString *cacheStr = [NSString stringWithFormat:@"%.2f M",cacheLength/(1024.0*1024.0)];
    if (cacheLength==0) {
        cacheStr = @"";
    }
    EpointSettingModel *cleanCache = [[EpointSettingModel alloc]initWithTitle:@"缓存清理" detail:@"" badge:cacheStr setClick:^{
        [self toastMessage:@"清理完成！"];
        [EpointIOUtil deleteFile:[EpointCacheDB getDBFilePath]];
        [self generateSetingData];
        [tv reloadData];
    }];
    [dataArray addObject:cleanCache];
    */
    
    EpointSettingModel *update = [[EpointSettingModel alloc]initWithTitle:@"软件升级" detail:@"" badge:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] setClick:^{
        [self startTask:@"EpointCheckUpdateTask" withParams:nil withTaskId:SetCheckUpdateTaskId];
    }];
    [dataArray addObject:update];
    
    EpointSettingModel *feedback = [[EpointSettingModel alloc]initWithTitle:@"问题反馈" detail:@"" badge:@"" setClick:^{
        [EpointInputViewController involeInputViewController:self vctitle:@"问题反馈" preContent:@"" handler:^(NSString *text){
            NSLog(@"%@",text);
            NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
            [params setObject:text forKey:@"feedbackcontent"];
            [self startTask:@"Task_FrameFeedBack" withParams:params withTaskId:FrameFeedBackTaskId];
        }];
    }];
    [dataArray addObject:feedback];
    EpointSettingModel *about = [[EpointSettingModel alloc]initWithTitle:@"关于" detail:@"" badge:@"" setClick:^{
//        EpointAboutViewController *a = [[EpointAboutViewController alloc]init];
//        [self.navigationController pushViewController:a animated:YES];
        EAD_About_ViewController *vc = [[EAD_About_ViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [dataArray addObject:about];
    
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
//    switch (section) {
//        case 0:
//            return @"设置";
//            break;
//        default:
//            return @"";
//    }
//    return nil;
//}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return dataArray.count;
    }
    else
    {
        return 1;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath indexAtPosition:0]==0)
    {
        EpointSettingModel *d = [dataArray objectAtIndex:indexPath.row];
        d.sc();
    }
    else if([indexPath indexAtPosition:0]==1)
    {
        [self logout];
    }
}

-(void)logout
{
    //取消用户pushToken
    if ([NSLocalizedString(@"PushMessageEnable", @"") isEqualToString:@"1"])
    {
        [self startTask:@"Task_DeletePushToken" withParams:nil withTaskId:DeletePushTokenTaskId];
    }
    
    [DBFrameService setSecurityKey:Epoint_User_Psw Value:@""];
    EpointAppDelegate *dele = [[UIApplication sharedApplication]delegate];
    
    dele.window.rootViewController =[[UINavigationController alloc]initWithRootViewController: dele.loginVC];
}

-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj
{
    [self hideMBPHUD];
    if (taskId==SetCheckUpdateTaskId) {
        [EpointUpdateService validateUpdateInfo:obj vc:self flag:1];
    }
    else if (taskId==SynTaskId)
    {
        [self generateSetingData];
        [tv reloadData];
    }
}

@end
